package com.igame.Utils;

import com.igame.entity.AreaInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AreaHierarchyBuilder {
    private List<AreaInfo> areas;
    private Map<String, AreaInfo> areaMap = new HashMap<>();
    private Map<String, List<AreaInfo>> childrenMap = new HashMap<>();

    public AreaHierarchyBuilder(List<AreaInfo> areas) {
        this.areas = areas;
        buildHierarchy();
    }

    private void buildHierarchy() {
        // 将所有区域放入映射中
        for (AreaInfo area : areas) {
            areaMap.put(area.getAreaCode(), area);
            childrenMap.put(area.getAreaCode(), new ArrayList<>());
        }

        // 构建层级关系
        for (AreaInfo area : areas) {
            String parentCode = area.getParentCode();
            if (parentCode != null) {
                List<AreaInfo> children = childrenMap.get(parentCode);
                if (children != null) {
                    children.add(area);
                }
            }
        }
    }

    public List<AreaInfo> getProvinces() {
        // 假设省级区域的 parentCode 为 null
        List<AreaInfo> provinces = new ArrayList<>();
        for (AreaInfo area : areas) {
            if (area.getParentCode() == null) {
                provinces.add(area);
            }
        }
        return provinces;
    }

    public List<AreaInfo> getCities(String provinceCode) {
        return childrenMap.get(provinceCode);
    }

    public List<AreaInfo> getDistricts(String cityCode) {
        return childrenMap.get(cityCode);
    }
}
